﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using VladanStrigoNET.Samples.Blogged.Models;

namespace VladanStrigoNET.Samples.Blogged.Controllers
{
    public class BlogController : Controller
    {
        private readonly IPostRepository _postRepository = null;

        public BlogController(IPostRepository postRepository)
        {
            _postRepository = postRepository;
        }

        [ControllerAction]
        public void About()
        {
            RenderView("About");
        }

        [ControllerAction]
        public void ShowPosts(DateTime? from, DateTime? to)
        {
            IList<Post> posts;

            if (from.HasValue && to.HasValue)
            {
                posts = _postRepository.GetPostsDuring(from.Value, to.Value);
            }
            else if (from.HasValue)
            {
                posts = _postRepository.GetPostsSince(from.Value);
            }
            else
            {
                posts = _postRepository.GetTopPosts();
            }


            if (posts.Count > 0)
            {
                base.RenderView("default", posts);
            }
            else
            {
                base.RenderView("nosuchposts");
            }
        }

        [ControllerAction]
        public void ShowPost(int id)
        {
            Post p = _postRepository.GetPostById(id);
            if (p != null)
            {
                RenderView("showpost", p);
            }
            else
            {
                RenderView("nosuchpost", id);
            }
        }

        [ControllerAction]
        public void AddNewPost()
        {
            if (Request.RequestType == "GET")
            {
                RenderView("newpost");
            }
            else if (Request.RequestType == "POST")
            {
                _postRepository.AddNewPost(Request.Form["title"], Request.Form["body"]);
                RedirectToAction("showposts");
            }
        }

        [ControllerAction]
        public void Delete(int id)
        {
            _postRepository.Delete(id);

            RedirectToAction("showposts");
        }
    }
}
